<template>
  <div>
    <el-form :model="templeInfo" label-width="100px">
      <el-form-item label="宗亲会名称">
        <el-input v-model="templeInfo.name" />
      </el-form-item>
      <el-form-item label="位置">
        <el-input v-model="templeInfo.location" disabled />
      </el-form-item>
      <el-form-item label="地理位置">
        <div class="map-container">
          <div id="map-container" class="amap-wrapper"></div>
          <div class="map-info">
            <p>经度: {{ templeInfo.longitude }}</p>
            <p>纬度: {{ templeInfo.latitude }}</p>
            <el-button type="primary" size="small" @click="showMapDialog = true"
              :disabled="isViewMode">选择位置</el-button>
          </div>
        </div>

        <el-dialog v-model="showMapDialog" title="选择位置" width="80%" :destroy-on-close="true">
          <div class="map-search-container">
            <el-input v-model="searchAddress" placeholder="输入地址搜索位置" @input="searchLocation" clearable  @keyup.enter="searchLocation">
              <template #append>
                <el-button @click="searchLocation">
                  <el-icon>
                    <Search />
                  </el-icon>
                </el-button>
              </template>
            </el-input>
            <div v-if="searchResults.length > 0" class="search-results">
              <div v-for="(item, index) in searchResults" :key="index" class="search-result-item"
                @click="useSearchResult(item)">
                {{ item.formattedAddress }}
              </div>
            </div>
          </div>
          <div style="height: 500px">
            <div id="map-dialog" style="height: 100%"></div>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="showMapDialog = false">取消</el-button>
              <el-button type="primary" @click="confirmLocation">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </el-form-item>
      <el-form-item label="简介">
        <WangEditor v-model="templeInfo.history" style="min-height: 200px;" />
      </el-form-item>

      <el-form-item label="收款码">
        <SingleImageUpload 
          v-model="templeInfo.qrcodeUrl" 
          :max-file-size="2"
          :style="{ width: '180px', height: '180px' }"
        />
        <div class="upload-tip">请上传微信或支付宝收款码，大小不超过2MB</div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveTempleInfo">保存信息</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import ClanAssociationAPI from "@/api/clan/clan-association"
import WangEditor from "@/components/WangEditor/index.vue"
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue"

const props = defineProps({
  templeId: {
    type: [String, Number],
    required: true
  },
  isViewMode: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:templeInfo'])

// 宗亲会信息
const templeInfo = ref({
  name: '江西博阳李氏宗亲会',
  location: '福建省厦门市思明区某某路123号',
  history: '这是一个具有悠久历史的宗亲会，始建于1900年，经过多代人的传承和发展，现已成为本地区最具影响力的宗亲组织之一。宗亲会致力于弘扬传统文化，增进宗亲情谊，促进社会和谐。',
  qrcodeUrl: '/src/assets/logo.png',
  longitude: 118.0894,
  latitude: 24.4798
})

// 地理位置相关变量
const showMapDialog = ref(false)
let map = null
let dialogMap = null
let marker = null
let tempLocation = { lng: null, lat: null }
const searchAddress = ref('')
const searchResults = ref([])
const AMAP_WEB_API_KEY = '9c5a053254c95d14843efc080ac74f78'
const AMAP_SECURITY_CODE = '59173e03758c881beab7c813d3a25329'

// 加载高德地图脚本
function loadAMap() {
  return new Promise((resolve, reject) => {
    window._AMapSecurityConfig = { securityJsCode: AMAP_SECURITY_CODE }
    if (window.AMap) return resolve(window.AMap)
    const script = document.createElement('script')
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_WEB_API_KEY}&plugin=AMap.Geocoder`
    script.async = true
    script.onload = () => resolve(window.AMap)
    script.onerror = (error) => reject(error)
    document.head.appendChild(script)
  })
}

// 初始化地图
function initMap() {
  if (!document.getElementById('map-container')) return
  if (!window.AMap) {
    loadAMap().then(() => setTimeout(() => initMap(), 500))
    return
  }
  map = new AMap.Map('map-container', {
    zoom: 11,
    resizeEnable: true,
    center: [templeInfo.value.longitude || 116.397428, templeInfo.value.latitude || 39.90923]
  })
  if (templeInfo.value.longitude && templeInfo.value.latitude) {
    marker = new AMap.Marker({
      position: [templeInfo.value.longitude, templeInfo.value.latitude],
      map: map
    })
    map.setCenter([templeInfo.value.longitude, templeInfo.value.latitude])
  }
}

// 初始化对话框地图
function initDialogMap() {
  if (!document.getElementById('map-dialog')) return
  if (!window.AMap) {
    loadAMap().then(() => setTimeout(() => initDialogMap(), 500))
    return
  }
  dialogMap = new AMap.Map('map-dialog', {
    zoom: 11,
    resizeEnable: true,
    center: [templeInfo.value.longitude || 116.397428, templeInfo.value.latitude || 39.90923]
  })
  if (templeInfo.value.longitude && templeInfo.value.latitude) {
    dialogMap.setCenter([templeInfo.value.longitude, templeInfo.value.latitude])
    tempLocation = {
      lng: templeInfo.value.longitude,
      lat: templeInfo.value.latitude
    }
    new AMap.Marker({
      position: [templeInfo.value.longitude, templeInfo.value.latitude],
      map: dialogMap
    })
  }
  dialogMap.on('click', function(e) {
    dialogMap.clearMap()
    new AMap.Marker({
      position: [e.lnglat.getLng(), e.lnglat.getLat()],
      map: dialogMap
    })
    tempLocation = {
      lng: e.lnglat.getLng(),
      lat: e.lnglat.getLat()
    }
    getAddressFromLocation(e.lnglat.getLng(), e.lnglat.getLat())
  })
}

// 通过经纬度获取地址
function getAddressFromLocation(lng, lat) {
  if (!window.AMap) return
  const geocoder = new AMap.Geocoder({ city: '全国' })
  geocoder.getAddress([lng, lat], function(status, result) {
    if (status === 'complete' && result.info === 'OK') {
      if (result.regeocode && result.regeocode.formattedAddress) {
        templeInfo.value.location = result.regeocode.formattedAddress
        templeInfo.value.longitude = lng
        templeInfo.value.latitude = lat
      }
    } else {
      templeInfo.value.location = `坐标位置(${lng.toFixed(6)}, ${lat.toFixed(6)})`
      templeInfo.value.longitude = lng
      templeInfo.value.latitude = lat
    }
  })
}

// 确认位置选择
function confirmLocation() {
  if (tempLocation.lng && tempLocation.lat) {
    templeInfo.value.longitude = tempLocation.lng
    templeInfo.value.latitude = tempLocation.lat
    if (map) {
      map.clearMap()
      marker = new AMap.Marker({
        position: [tempLocation.lng, tempLocation.lat],
        map: map
      })
      map.setCenter([tempLocation.lng, tempLocation.lat])
    }
  }
  showMapDialog.value = false
}

// 搜索地址
function searchLocation() {
  if (!searchAddress.value || !window.AMap) return
  AMap.plugin('AMap.Geocoder', function() {
    const geocoder = new AMap.Geocoder({ city: '全国' })
    geocoder.getLocation(searchAddress.value, function(status, result) {
      if (status === 'complete' && result.info === 'OK') {
        if (result.geocodes && result.geocodes.length > 0) {
          searchResults.value = result.geocodes
          if (result.geocodes.length === 1) {
            useSearchResult(result.geocodes[0])
          }
        } else {
          ElMessage.warning('未找到匹配的地址')
          searchResults.value = []
        }
      } else {
        ElMessage.error('地址搜索失败')
        searchResults.value = []
      }
    })
  })
}

// 使用搜索结果
function useSearchResult(item) {
  if (!dialogMap || !item || !item.location) return
  const location = item.location
  tempLocation = { lng: location.lng, lat: location.lat }
  dialogMap.clearMap()
  new AMap.Marker({ position: [location.lng, location.lat], map: dialogMap })
  dialogMap.setCenter([location.lng, location.lat])
  dialogMap.setZoom(15)
  templeInfo.value.location = item.formattedAddress
  templeInfo.value.longitude = location.lng
  templeInfo.value.latitude = location.lat
  searchResults.value = []
}

// 获取宗亲会详情
const getClanAssociationDetail = async () => {
  try {
    const response = await ClanAssociationAPI.getDetail(props.templeId)
    console.log(response, props.templeId)
    
    if (response) {
      // 将获取到的数据赋值到宗亲会信息中
      templeInfo.value = {
        id: response.id,
        name: response.name || '江西博阳李氏宗亲会',
        location: response.location || '福建省厦门市思明区某某路123号',
        history: response.history || '这是一个具有悠久历史的宗亲会，始建于1900年，经过多代人的传承和发展，现已成为本地区最具影响力的宗亲组织之一。宗亲会致力于弘扬传统文化，增进宗亲情谊，促进社会和谐。',
        qrcodeUrl: response.qrcodeUrl || '/src/assets/logo.png',
        longitude: response.longitude || 118.0894,
        latitude: response.latitude || 24.4798
      }
      emit('update:templeInfo', templeInfo.value)
    }
  } catch (error) {
    console.error('获取宗亲会详情失败：', error)
    ElMessage.error('获取宗亲会详情失败')
  }
}

// 宗亲会信息管理
const saveTempleInfo = async () => {
  try {
    // 这里应该调用API保存宗亲会信息
    await ClanAssociationAPI.update(props.templeId, templeInfo.value)
    ElMessage.success('保存成功')
    emit('update:templeInfo', templeInfo.value)
  } catch (error) {
    console.error('保存宗亲会信息失败：', error)
    ElMessage.error('保存失败')
  }
}

// 监听地图弹窗打开，初始化地图
watch(showMapDialog, (newVal) => {
  if (newVal) {
    nextTick(() => {
      setTimeout(() => {
        if (window.AMap) {
          initDialogMap()
        } else {
          loadAMap().then(() => initDialogMap())
        }
      }, 500)
    })
  } else {
    searchAddress.value = ''
    searchResults.value = []
  }
})

// 组件挂载后初始化
onMounted(() => {
  // 获取宗亲会详情
  getClanAssociationDetail()
  
  nextTick(() => {
    setTimeout(() => {
      if (window.AMap) {
        initMap()
      } else {
        loadAMap().then(() => initMap())
      }
    }, 500)
  })
})
</script>

<style scoped>
.map-container {
  display: flex;
}

.map-info {
  margin-left: 20px;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 5px;
}

.amap-wrapper {
  width: 300px;
  height: 200px;
  border: 1px solid #ddd;
  position: relative;
  overflow: hidden;
}

.map-search-container {
  margin-bottom: 10px;
}

.search-results {
  margin-top: 10px;
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.search-result-item {
  padding: 8px 12px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.search-result-item:hover {
  background-color: #f5f5f5;
}

.search-result-item:last-child {
  border-bottom: none;
}
</style> 